package com.google.code.jtasks.server.resources;

import com.google.code.jtasks.server.dao.TaskDAO;
import com.google.code.jtasks.common.data.Task;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.Collection;

/**
 * A REST resource endpoint for tasks management.
 */
@Path("/tasks")
public class TasksResource {
    private static final Logger LOG = LoggerFactory.getLogger(TasksResource.class);

    private final TaskDAO taskDAO;


    @Inject
    public TasksResource(TaskDAO taskDAO) {
        this.taskDAO = taskDAO;

    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Collection<Task> taskList() {
        LOG.debug("Get task list request received");
        return taskDAO.loadAllTasks();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{id}")
    public Response getTask(@PathParam("id") String taskId) {
        LOG.debug("Get task request received: task id {}", taskId);
        Optional<Task> task = taskDAO.loadTask(taskId);
        if (task.isPresent()) {
            return Response.ok(task.get()).build();
        } else {
            return Response.status(404).build();
        }
    }


    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response postTask(Task task) {
        LOG.debug("Create task request received: {}", task);
        String id = taskDAO.saveTask(task);
        return Response.created(URI.create("http://localhost:8080/tasks/" + id)).build();
    }

    @DELETE
    @Path("/{id}")
    public Response deleteTask(@PathParam("id") String taskId) {
        LOG.debug("Delete task request received: task id {}", taskId);
        if (taskDAO.deleteTask(taskId)) {
            return Response.ok().build();
        } else {
            return Response.status(404).build();
        }
    }
}
